import sympy as sp
import numpy as np
import matplotlib.pyplot as plt

# 定义符号变量和函数
x = sp.symbols('x')
f = sp.cos(x)

# 计算泰勒级数
taylor_order = 4  # 泰勒级数的阶数
taylor_series = sp.series(f, x, 4, taylor_order).removeO()  # 在 x=0 处展开，并移除高阶余项

# 将符号表达式转换为可计算的函数
taylor_func = sp.lambdify(x, taylor_series, 'numpy')
original_func = sp.lambdify(x, f, 'numpy')

# 定义绘图范围
x_vals = np.linspace(0, 2 * np.pi, 400)
y_original = original_func(x_vals)
y_taylor = taylor_func(x_vals)

# 绘图
plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_original, label="Original Function: cos(x)", color='blue')
plt.plot(x_vals, y_taylor, label=f"Taylor Approximation (Order {taylor_order})", color='red', linestyle='--')
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.xlabel('x')
plt.ylabel('y')
plt.title(f'Taylor Series Approximation of sin(x) (Order {taylor_order})')
plt.legend()
plt.grid(True)
plt.show()
